const app = getApp();
var Wxmlify = require('../../wxmlify/wxmlify.js');

Page({
  data: {
    courseList: [],
    shareUrl: null,
    isPay: false,
    course: null,
    courseId: null,
    actionSheetHidden: true
  },

  listenerButton: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    });
  },

  listenerActionSheet: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },

  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e);
    wx.request({
      url: app.globalData.serverUrl + '/payment/sendTemplateMessage',
      data: {
        fromId: e.detail.formId,
        openId: "oIpBo5JXWhn8XhqRbjeJYBZxT8Ms",
        templateId: "xCn8Kj7TJXCf_sWkGfEWu0DnqCyJxUU4luszlc_MmEQ"
      },
      success(resp) {
        if (resp.data.success) {

        }
      }
    });
  },

  a() {
    
  },

  b() {
    // wx.saveImageToPhotosAlbum
  },

  share2friend() {
    let that = this;

    // wx.showActionSheet({
    //   itemList: ['发送给好友', '生产分享图片'],
    //   success: function (res) {
    //     if (!res.cancel) {
    //       console.log(res.tapIndex);
    //       if (res.tapIndex == 0)
    //         that.a();
    //       if (res.tapIndex == 1)
    //         that.b();
    //     }
    //   }
    // });

    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    });

  },

  getCourseListByCourseId: function () {
    var that = this;

    wx.request({
      url: app.globalData.serverUrl + '/courseDetail/getCourseListByCourseId',
      data: {
        courseId: this.data.course.id,
        employeeId: app.globalData.employeeId == null ? 0 : app.globalData.employeeId
      },
      success(resp) {
        if (resp.data.success) {
          that.setData({
            courseList: resp.data.data,
            isPay: resp.data.isPay
          });
        }
      }
    });
  },

  onLoad: function (options) {
    console.log(options);
    var that = this;
    wx.showLoading({
      title: '加载中...',
    });

    // 为了做分享这个页面必须通过id从后台读取
    wx.request({
      url: app.globalData.serverUrl + '/course/queryById',
      data: {
        id: options.courseId
      },
      success(resp) {
        wx.hideLoading();
        if (resp.data.success) {
          that.setData({
            course: resp.data.data
          });

          // 查询课程列表
          that.getCourseListByCourseId();
        }
      },
      fail(e) {
        wx.hideLoading();
      }
    });

    // 查询课程详情html
    wx.request({
      url: app.globalData.serverUrl + '/courseDetail/getCourseByCourseId',
      data: {
        id: options.courseId
      },
      success(resp) {
        wx.hideLoading();
        if (resp.data.success) {
          let html = resp.data.data.detail;
          var wxmlify = new Wxmlify(html, that, {});
        }
      },
      fail(e) {
        wx.hideLoading();
      }
    });

  },

  onShareAppMessage: function (e) {
    // console.log(e);
    return {
      title: this.data.course.title,
      imageUrl: this.data.course.logo,
      path: "/pages/list/index?courseId=" + this.data.course.id + "&openid=" + app.globalData.openid,
      success: function (res) {
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        wx.getShareInfo({
          shareTicket: shareTickets[0],
          success: function (res) {
            var encryptedData = res.encryptedData;
            var iv = res.iv;
          }
        })
      },
      fail: function (res) {
        // 转发失败
        console.log(res);
      }
    }
  },

  viewBindtap(e) {
    console.log(e);

    if (e.currentTarget.dataset.obj.tryout == 1) {
      if (this.data.course.courseType == "courseType_01") {
        wx.navigateTo({
          url: '../audio/index?id=' + e.currentTarget.dataset.obj.id + '&poster=' + this.data.course.logo
        });
      }

      if (this.data.course.courseType == "courseType_02") {
        wx.navigateTo({
          url: '../video/index?id=' + e.currentTarget.dataset.obj.id + '&poster=' + this.data.course.logo
        });
      }

      return;
    }

    if (!this.data.isPay) {
      wx.showToast({
        icon: 'none',
        title: '未购买!',
      })
      return;
    }

    if (this.data.course.courseType == "courseType_01") {
      wx.navigateTo({
        url: '../audio/index?id=' + e.currentTarget.dataset.obj.id + '&poster=' + this.data.course.logo
      });
    }

    if (this.data.course.courseType == "courseType_02") {
      wx.navigateTo({
        url: '../video/index?id=' + e.currentTarget.dataset.obj.id + '&poster=' + this.data.course.logo
      });
    }

  },

  showPayDlg(orderNu) {
    var that = this;
    var total_fee = this.data.course.price;
    total_fee = (parseFloat(total_fee) * 100).toFixed();
    console.log(total_fee, total_fee);

    wx.request({
      url: app.globalData.serverUrl + "/payment/getPaySign",
      data: {
        body: this.data.course.name,
        out_trade_no: orderNu,
        total_fee: total_fee,
        openid: app.globalData.openid
      },
      success(resp) {
        if (resp.data.success) {
          wx.requestPayment({
            'timeStamp': resp.data.data.timeStamp,
            'nonceStr': resp.data.data.nonceStr,
            'package': resp.data.data.package,
            'signType': 'MD5',
            'paySign': resp.data.sign,
            'success': function (res) {
              console.log(res);

              var options = {};
              options.courseId = that.data.course.id;
              that.onLoad(options);
            },
            'fail': function (res) {
              console.log(res);
            }
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: resp.data.errorMsg,
          })
        }
      },
      fail(resp) {
        console.log(resp);
      }
    });
  },

  weixpay(e) {
    if (this.data.course.courseType == "courseType_03") {
      wx.navigateTo({
        url: '../book/index?course=' + JSON.stringify(this.data.course)
      })
      return;
    }

    let that = this;
    let obj = {};
    obj.type = this.data.course.courseType;
    obj.employeeId = app.globalData.employeeId;
    if (obj.employeeId == null) {
      wx.navigateTo({
        url: '../register/index',
      })
      return;
    }

    let orderDetailList = [];
    let obj2 = {};
    obj2.merchandiseId = this.data.course.id;
    obj2.name = this.data.course.name;
    obj2.price = this.data.course.price;
    obj2.amount = 1;
    obj2.sumPrice = this.data.course.price * obj2.amount;
    orderDetailList.push(obj2);

    obj.sumPrice = obj2.sumPrice;

    obj.orderDetail = orderDetailList;
    wx.request({
      method: "POST",
      url: app.globalData.serverUrl + "/order/create",
      data: obj,
      success(resp) {
        if (resp.data.success) {
          that.showPayDlg(resp.data.data.id);

        } else {
          wx.showToast({
            icon: 'none',
            title: resp.data.errorMsg,
          });
        }
      },
      fail(resp) {
        wx.showToast({
          icon: 'none',
          title: JSON.stringify(resp)
        });
      }
    });
  },

})